import 'package:flutter/widgets.dart';

typedef FloatingIndexTouchCallback(String item,int index);
typedef FloatingIndexRenderItem(BuildContext context, String item,int index);

/// 浮动索引
class FloatingIndex extends StatefulWidget {
  FloatingIndex({
    Key key, 
    @required this.data, 
    this.onTap,
    @required this.renderItem, 
    this.itemHeight = 20,
    this.itemWidth = 20,
  }) : super(key: key);
  /// 索引数据
  final List<String> data;  
  /// 点击回调事件
  final FloatingIndexTouchCallback onTap;
  /// 渲染索引节点
  final FloatingIndexRenderItem renderItem;
  /// 渲染的索引节点高度
  final double itemHeight;
  /// 渲染的索引节点宽度
  final double itemWidth;
  
  _FloatingIndexState createState() => _FloatingIndexState();
}

class _FloatingIndexState extends State<FloatingIndex> {
  _triggerTouch(int index) {
    widget.onTap(widget.data.elementAt(index), index);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onVerticalDragDown: (DragDownDetails details) {
        int offset = details.globalPosition.dy.toInt();
        RenderBox rb = context.findRenderObject();
        int top = rb.localToGlobal(Offset.zero).dy.toInt();
        _triggerTouch(((offset - top) / widget.itemHeight).floor());
      },
      onVerticalDragUpdate: (DragUpdateDetails details) {
        int offset = details.globalPosition.dy.toInt();
        RenderBox rb = context.findRenderObject();
        int top = rb.localToGlobal(Offset.zero).dy.toInt();
        int index = ((offset - top) / widget.itemHeight).floor();
        _triggerTouch(index.clamp(0, widget.data.length - 1));
      },
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: widget.data.map((item){
          int index = widget.data.indexOf(item);
          return SizedBox(
            child: widget.renderItem(context, item, index),
            height: widget.itemHeight,
            width: widget.itemWidth,
          );
        }).toList(),
      ),
    );
  }
}